<?php

/** Zend_View */
require_once 'Zend/View.php';

/** 
 * Zps_View_Interface
 */
require_once 'Zps/View/Interface.php';

/** 
 * Zps_View_Factory
 */
require_once 'Zps/View/Factory.php';

/** 
 * Zend_Registry
 */
require_once 'Zend/Registry.php';

class Zps_View extends Zend_View implements Zps_View_Interface
{

    /**
     * Includes a sub-View by reference to the template filename
     * and the Module it's located in assuming the recommended
     * basePath is adhered to as a convention.
     *
     * @param string $file
     * @param string $module
     * @param array $params
     * @return string
     */
    public function attach($file, $module = null, array $params = null)
    {
        $viewFactory = $this->_factory();
        $subView = $viewFactory->createInstance($module, $this, $params);
        return $subView->render($file);
    }

    /**
     * Set a main parent View sourced from each Request's controller.
     *
     * @param Zend_View_Interface $view
     * @return Zps_View
     */
    public function setMainView(Zend_View_Interface $view)
    {
        $this->_mainView = $view;
        return $this;
    }

    /**
     * Get the main parent View.
     *
     * @return Zps_View
     */
    public function getMainView()
    {
        if (!isset($this->_mainView)) {
            return $this;
        }
        return $this->_mainView;
    }

    /**
     * Method to clone this View assuming the sub-View (the clone) is from
     * the same application Module as the original.
     * Here we are simply getting rid of the inherited public variables which
     * represent the ancestor View's model.
     *
     * @return null
     */
    public function __clone()
    {
        foreach(get_object_vars($this) as $key=>$value) {
            $this->__unset($key);
        }
    }

    /**
     * Fetch an instance of Zps_View_Factory which should be present in
     * in the default instance of Zend_Registry.
     *
     * @param  null
     * @return Zps_View_Factory
     */
    protected function _factory()
    {
        if (!Zend_Registry::isRegistered('ViewFactory')) {
            throw new Zps_View_Exception('Registry does not contain an entry for the ViewFactory');
        } else {
            $viewFactory = Zend_Registry::get('ViewFactory');
        }
        return $viewFactory;
    }

}